<template>
  <div class="main">
    <div class="maintop">
      <span>中铁十二局电子签名系统</span>
    </div>
    <div class="boxtit1">徐州地铁SGTJ6107标</div>
    <div class="maincont">
      <div class="vid">
        <button @click="openMedia()">开启摄像头</button>
        <div class="pho">
          <video id="video" autoplay="autoplay"></video>
        </div>
        <canvas id="canvasE" width="500px" height="500px"></canvas>
        <button @click="takePhoto()">拍照</button>

        <button @click="closeMedia()">关闭摄像头</button>
      </div>

      <div class="signatureBox">
        <div class="canvasBox" ref="canvasHW">
          <canvas
            id="canvasF"
            ref="canvasF"
            @touchstart="touchStart"
            @touchmove="touchMove"
            @touchend="touchEnd"
            @mousedown="mouseDown"
            @mousemove="mouseMove"
            @mouseup="mouseUp"
          ></canvas>
        </div>
      </div>
    </div>
    <div class="btnBox">
      <button @click="commit"></button>
      <button @click="overwrite"></button>
      <button @click="gomain"></button>
    </div>
  </div>
</template>

<script>
let mediaStreamTrack = null; // 视频对象(全局)
let video;

export default {
  data() {
    return {
      stageInfo: "",
      imgUrl: "",
      client: {},
      points: [],
      canvasTxt: null,
      startX: 0,
      startY: 0,
      moveY: 0,
      moveX: 0,
      endY: 0,
      endX: 0,
      w: null,
      h: null,
      isDown: false,
      isViewAutograph: this.$route.query.isViews > 0,
      contractSuccess: this.$route.query.contractSuccess,
    };
  },
  mounted() {
    let canvas = this.$refs.canvasF;
    canvas.height = this.$refs.canvasHW.offsetHeight + 1;
    canvas.width = this.$refs.canvasHW.offsetWidth - 1;
    this.canvasTxt = canvas.getContext("2d");
    this.stageInfo = canvas.getBoundingClientRect();
    //进入页面加载完成后直接打开摄像头
    if (document.readyState === "complete") {
      this.openMedia();
    } else {
      document.addEventListener("load", () => this.openMedia());
    }
  },
  methods: {
    gomain() {
      this.$router.push("/");
    },
    //视频逻辑
    openMedia() {
      let constraints = {
        video: {
          width: 500,
          height: 500,
        },
        audio: false,
      };
      //获得video摄像头
      video = document.getElementById("video");
      let promise = navigator.mediaDevices.getUserMedia(constraints);
      promise.then((mediaStream) => {
        // mediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[1];
        mediaStreamTrack = mediaStream.getVideoTracks();
        video.srcObject = mediaStream;
        video.play();
      });
    },
    // 拍照
    // takePhoto() {
    //   //获得Canvas对象
    //   let video = document.getElementById("video");
    //   let canvasE = document.getElementById("canvasE");
    //   let ctx = canvasE.getContext("2d");
    //   ctx.drawImage(video, 0, 0, 500, 500);

    //   // toDataURL  ---  可传入'image/png'---默认, 'image/jpeg'
    //   let img = document.getElementById("canvasE").toDataURL();
    //   // 这里的img就是得到的图片
    //   console.log("img-----", img);
    //   document.getElementById("imgTag").src = img;
    //   //上传
    //   $.ajax({
    //     url: "/xxxx.do",
    //     type: "POST",
    //     data: {
    //       imgData: img
    //     },
    //     success: function(data) {
    //       console.log(data);
    //       document.gauges.forEach(function(gauge) {
    //         gauge.value = data.data;
    //       });
    //     },
    //     error: function() {
    //       console.log("服务端异常！");
    //     }
    //   });
    // },
    // 关闭摄像头
    closeMedia() {
      let stream = document.getElementById("video").srcObject;
      let tracks = stream.getTracks();

      tracks.forEach(function (track) {
        track.stop();
      });

      document.getElementById("video").srcObject = null;
    },

    //签名逻辑 mobile

    touchStart(ev) {
      ev = ev || event;
      ev.preventDefault();
      // let video = document.getElementById("video");
      let canvasF = document.getElementById("canvasF");
      let ctx = canvasF.getContext("2d");
      ctx.lineWidth = 10;
      ctx.strokeStyle = "#fff";
      ctx.lineCap = "round"; //去锯齿
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clienX,
          y: ev.targetTouches[0].clientY,
        };
        this.startX = obj.x;
        this.startY = obj.y;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
      }
    },
    touchMove(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clientX - this.stageInfo.left,
          y: ev.targetTouches[0].clientY - this.stageInfo.top,
        };
        this.moveY = obj.y;
        this.moveX = obj.x;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.startY = obj.y;
        this.startX = obj.x;
        this.points.push(obj);
      }
    },
    touchEnd(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clientX - this.stageInfo.left,
          y: ev.targetTouches[0].clientY - this.stageInfo.top,
        };
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
      }
    },
    //pc///////////////////////////////////////////////////////////

    mouseDown(ev) {
      ev = ev || event;
      ev.preventDefault();
      let video = document.getElementById("video");
      let canvasF = document.getElementById("canvasF");
      let ctx = canvasF.getContext("2d");
      ctx.lineWidth = 10;
      ctx.strokeStyle = "#fff";
      ctx.lineCap = "round";

      if (1) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.startX = obj.x;
        this.startY = obj.y;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
        this.isDown = true;
      }
    },
    mouseMove(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (this.isDown) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.moveY = obj.y;
        this.moveX = obj.x;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.startY = obj.y;
        this.startX = obj.x;
        this.points.push(obj);
      }
    },
    mouseUp(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (1) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
        this.points.push({ x: -1, y: -1 });
        this.isDown = false;
      }
    },
    //重写
    overwrite() {
      this.canvasTxt.clearRect(
        0,
        0,
        this.$refs.canvasF.width,
        this.$refs.canvasF.height
      );
      this.points = [];
    },
    //提交签名
    commit() {
      this.imgUrl = this.$refs.canvasF.toDataURL();
      console.log("imgvideo-----", this.$refs.canvasF.toDataURL()); //签名img回传后台
      this.$router.push("/");

      //上传签名的同时拍照，然后显示图片    ////////////////////////////////
      //获得Canvas对象
      let video = document.getElementById("video");
      let canvasE = document.getElementById("canvasE");
      let ctx = canvasE.getContext("2d");
      ctx.drawImage(video, 0, 0, 620, 500);

      // toDataURL  ----  可传入'image/png'---默认, 'image/jpeg'
      this.imgUrl1 = document.getElementById("canvasE").toDataURL();
      // 这里的img就是得到的图片
      console.log("imgsign-----", this.imgUrl1);
      // document.getElementById("imgTag").src = this.imgUrl1;

      //发送后台请求  以map的形式把两张图片同时传给后端//////////////////////////////////
      var parameter = {
        imgStr: this.imgUrl1,
        imgStr1: this.imgUrl,
      };
      $.ajax({
        type: "POST",
        url: "http://101.132.154.10:8189/upload/base64_img",
        contentType: "application/json",
        data: JSON.stringify(parameter),
        success: function (data) {
          console.log("成功");
        },
      });
    },
  },
};
</script>

<style scoped=''>
html,
body {
  margin: 0;
}
* {
  padding: 0;
  margin: 0;
}

.main {
  width: 100%;
  height: 100%;
  /* overflow: hidden; */
  background: url(../assets/images/back1.png) no-repeat;
  background-size: 100% 100%;
  min-height: 100vh;
  /* justify-content: flex-start; */
  display: flex;
  align-items: center;
  flex-direction: column;
}
/* //////////////////////////////////////////////////////////// */
.main .maintop {
  width: 100%;
  height: 0.9rem;
  font-size: 0.40rem;
  line-height: 0.9rem;
  font-weight: 700;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: center;
  display: flex;
  /* align-items: center; */
  font-family: Source Han Sans CN;
  font-weight: bold;
  color: rgba(255, 229, 53, 1);
  letter-spacing: 5px;
  /* background: blueviolet; */
}
.main .maintop span {
  width: 5rem;
  height: 0.9rem;
  justify-content: center;
  display: flex;
  align-items: center;
  line-height: 0.9rem;
  /* background: yellowgreen; */
}
.boxtit1 {
  text-align: center;
  width: 4.5rem;
  height: 0.4rem;
  font-size: 0.25rem;
  line-height: 0.25rem;
  font-weight: 700;
  color: #9dc9cf;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: center;
  display: flex;
  align-items: center;
  font-family: Source Han Sans CN;
  font-weight: bold;
  color: rgba(0, 237, 248, 1);
  letter-spacing: 5px;
  background: url(../assets/images/yu.png) no-repeat;
  background-size: 100% 100%;
}
/* ///////////////////////////////////////////////////////////////////////////// */
.main .maincont {
  margin-top: 0.35rem;
  width: 83%;
  /* height: 65%; */
  background: rgba(13, 98, 172, 1);
  opacity: 0.5;
  flex: 1;
  display: flex;
  flex-direction: row;
}
.main .maincont .vid {
  width: 3.5rem;
  height: 2.65rem;
  background: rgb(6, 9, 12);
  float: left;
}
#canvasE {
  display: none;
}
.main .maincont .vid button {
  display: none;
}
.main .maincont .vid .pho {
  width: 3.5rem;
  height: 2.65rem;
}
.main .maincont .vid .pho #video {
  width: 100%;
  height: 100%;
}

.main .maincont .signatureBox {
  float: left;

  flex: 1;
  height: 7.5rem;
  /* background: rgb(94, 74, 74); */
}
.main .maincont .signatureBox .canvasBox {
  width: 12.4rem;
  height: 7.5rem;
  /* background: red */
}
/* //////////////////////////11111111111111111111111111111111111111////////////////////////////////// */
.main .btnBox {
  /* margin-top: 0.05rem; */
  width: 40%;
  height: 1.59rem;
  /* background: yellowgreen; */
  justify-content: center;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
.btnBox button:first-child {
  height: 0.8rem;
  width: 1.8rem;
  background: url(../assets/images/commit.png) no-repeat;
  background-size: 100% 100%;
  border: none;
}
.btnBox button:nth-child(2) {
  height: 0.8rem;
  width: 1.8rem;
  background: url(../assets/images/resign.png) no-repeat;
  background-size: 100% 100%;
  border: none;
}
.btnBox button:last-child {
  height: 0.8rem;
  width: 1.8rem;
  background: url(../assets/images/cancl.png) no-repeat;
  background-size: 100% 100%;
  border: none;
}
</style>